#!/bin/bash

# 设置脚本在遇到错误时立即退出
set -e

# 容器名称
CONTAINER_NAME="${project.build.finalName}"
# 镜像名称
IMAGE_NAME="${project.build.finalName}:last"
# 暴漏端口
CONTAINER_PORT="${server.port}"

# 如果输入格式不对，给出提示！
tips() {
	echo ""
	echo "Tips, please use command: sh auto_deploy.sh [start|stop|restart|status]. For example: sh docker.sh start"
	echo ""
	exit 1
}

stop() {

    # 使用docker ps命令查找容器是否存在
    if docker ps -a --format '{{.Names}}' | grep -q "$CONTAINER_NAME"; then
        echo "Stopping running container..."
        docker stop "${CONTAINER_NAME}"
        echo "Removing stopped container..."
        docker rm -f "${CONTAINER_NAME}"
    else
        echo "容器不存在..."
    fi

}

start() {

    echo "Building new image..."
    docker build -t "${IMAGE_NAME}" .

    # 使用docker ps命令查找容器是否存在
    if docker ps -a --format '{{.Names}}' | grep -q "$CONTAINER_NAME"; then
        echo "容器存在,启动失败..."
    else
        echo "Starting new container..."
        docker run -d --name "${CONTAINER_NAME}" \
            --cap-add=SYS_PTRACE \
            -p ${CONTAINER_PORT}:${CONTAINER_PORT} \
            -v "$(pwd)/dumps:/app/dumps" \
            -v "$(pwd)/logs:/app/logs" \
            "${IMAGE_NAME}"
        echo "Container has been restarted."
    fi
}

restart(){
    stop
    start
}

status(){

  # 使用docker ps命令查找容器是否存在
  if docker ps -a --format '{{.Names}}' | grep -q "$CONTAINER_NAME"; then
      echo "容器存在..."
  else
      echo "容器不存在..."
  fi

}


# 根据输入参数执行对应方法，不输入则执行tips提示方法
case "$1" in
   "start")
     start
     ;;
   "stop")
     stop
     ;;
   "status")
     status
     ;;
   "restart")
     restart
     ;;
   *)
     tips
     ;;


esac
